<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <h1>02</h1>
    <button onclick="doAjaxGet()">添加</button>
    <button onclick="doAjaxPost()">Post</button>
    <button onclick="doAjaxDelete()">删除</button>
    <button onclick="doAjaxUpdate()">put</button>
</div>
<div id="result"></div>
<script>

    //Ajax Get请求方式应用,此方式主要用于服务器获取数据
    function doAjaxGet() {
        let xhr=new XMLHttpRequest();
        xhr.onreadystatechange=function () {
        if (xhr.readyState==4){
            if (xhr.status==200){ document.getElementById("result").innerHTML=xhr.responseText;}

        }
        }
        xhr.open("get","doAjaxGet",true)
        xhr.send(null);
    }
    function doAjaxPost() {
        let xhr=new XMLHttpRequest();
        xhr.onreadystatechange=function () {
            if (xhr.readyState==4){
                if (xhr.status==200){ document.getElementById("result").innerHTML=xhr.responseText;}

            }
        }
        //当做一个添加操作,或者 向服务端提交的数据比较多时可以考虑使用post请求
        xhr.open("post","doAjaxPost",true);
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xhr.send("id=200&name=xiaomi&remark=good");//post请求数据写到send方法内部
    }
    function doAjaxDelete(){
        let xhr=new XMLHttpRequest();
        xhr.onreadystatechange=function () {
            if (xhr.readyState==4){
                if (xhr.status==200){ document.getElementById("result").innerHTML=xhr.responseText;}

            }
        }
        xhr.open("delete","doAjaxDelete?id=200",true);
        xhr.send(null);
    }
    function doAjaxUpdate(){
        let xhr=new XMLHttpRequest();
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    document.getElementById("result").innerHTML=xhr.responseText;
                }
            }
        }
        xhr.open("put","http://localhost/doAjaxUpdate",true);
        //post请求向服务端传递数据,需要设置请求头,必须在open之后
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        //发送请求(post请求传递数据,需要将数据写入到send方法内部)
        xhr.send("id=200&name=oppo&remark=nice...");
    }
</script>

</body>
</html>